<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="portal" uri="/WEB-INF/portal.tld" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <%@ include file="/common/plateform/include/common-base.jsp"%>
  <title>权限分配</title>
  <!-- Tell the browser to be responsive to screen width -->
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
</head>

<!-- Part 一、 以下是body主体内容的模块区域 -->
<body class="hold-transition ${sysColor} sidebar-mini">
<div class="wrapper">

  <!-- top start -->
  <%@include file="/common/plateform/top.jsp" %>
  <!-- top end -->
  <!-- left start -->
  <%@include file="/common/plateform/left-project.jsp" %>
  <!-- left end-->

	<div class="content-wrapper">
		<!-- Main start -->
		<section class="content">
			<div id="div_hidden_content" class="hidden" style="display:none;">
				<div id="hidden_common_final">
					<!-- temp="hidden_common_final" start -->
					<input name="mainObjName" type="hidden" value="hsMember">
					<input name="mainObjPrimaryKey" type="hidden" value="userId">
					<input name="objNameAll" type="hidden" value="hsMember">
					<!-- temp="hidden_common_final" end -->
				</div>
				<!-- temp="delForm_hidden" start -->
				<!-- temp="delForm_hidden" end -->
			</div>
			<div class="row">
				<div class="col-xs-12">

					<!------搜索  start ------->
					<div class="box box-info">
						<!--搜索title  start -->
						<div class="box-header with-border">
							<h3 class="box-title"><i class="fa fa-search"></i> 管理人员搜索</h3>
							<div class="box-tools pull-right">
								<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
							</div>
						</div>
						<!--搜索title  end -->
						<div class="box-body">
							<form id="searchForm" action="javascript:;">
								<!-- temp="searchForm_hidden" start -->
								<div id="searchForm_hidden">
									<input type="hidden" name="pageName" value="uct-user-sys-list"/>
									<input type="hidden" name="formName" value="searchForm"/>
									<input type="hidden" name="uctUserSys.w_sysNo" value=""/>
									<input type="hidden" name="orderBy" value="uctUserSys.create_time desc"/>
								</div>
								<!-- temp="searchForm_hidden" end -->
								<!-- temp="searchForm_content" start -->
								<div id="searchForm_content" class="form-group"  data-temp-code="true" data-temp-type="searchForm" data-temp-form-id="searchForm">




									<table class="table table-bordered bordercolor">
										<tbody>
										<tr>
											<td class="active" align="right"><label class="form-control-static">登录账号：</label></td>
											<td>
												<div class="form-group"><input name="uctUser.wl_userEname" class="form-control clean"
																			   maxlength="30" data-temp-obj="uctUser.userEname"></div>
											</td>
											<td class="active" align="right"><label class="form-control-static">用户名称：</label></td>
											<td>
												<div class="form-group"><input name="uctUser.wl_userCname" class="form-control clean"
																			   maxlength="30" data-temp-obj="uctUser.userCname"></div>
											</td>
										</tr>
										</tbody>
									</table>

								</div>
								<!-- temp="searchForm_content" end -->
							</form>
							<div class="box-footer text-center">
								<button type="button" class="btn btn-success" onclick="getTableData();" data-temp-event="searchForm_hidden"><i class="fa fa-search"></i> 查询</button> 
								<button type="button" class="btn btn-warning" onclick="mytools.cleanData('#searchForm');">重置 </button>
							</div>
						</div>
					</div>
					<!------- 搜索 end -------->

					<!------- 列表 start -------->
					<div class="box box-success">
						<!--列表title  start -->
						<div class="box-header with-border">
							<h3 class="box-title"><i class="fa fa-table"></i> 查询结果
								　　　              <button id="button_to_add" onclick="toAddAct();" class="btn btn-primary" type="button"><i class="fa fa-plus-circle"></i> 权限分配 </button>
							</h3>
							<div class="box-tools pull-right">
								<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
							</div>
						</div>
						<div class="box-body">
							<table id="dataList" class="table table-bordered table-hover">
								<thead class="bg-success">
								<tr id="dataList_thead_content" data-temp-code="true" data-temp-type="table" data-temp-show="dataList_template_content">
									<th>序号</th>
									<!-- temp="dataList_thead_content" start -->

									<th data-temp-obj="uctUserSys.userEname">用户账号</th>
									<th data-temp-obj="uctUser.userCname">用户名称</th>
									<th data-temp-obj="uctUser.delStatus">用户类别</th>
									<th data-temp-obj="uctUser.mobile">手机</th>
									<th data-temp-obj="uctUserSys.createTime">添加时间</th>
									<!-- temp="dataList_thead_content" end -->
								</tr>
								</thead>
								<tbody id="dataList-body">

								</tbody>
							</table>
						</div>

						<div class="box-footer text-center">
							<ul id="dataList-page" class="pagination">
							</ul>
						</div>
					</div>
					<!------- 列表 end -------->
				</div>
			</div>
			<div win-title="权限窗口" class="modal fade" id="my_modal_act" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
				<div class="modal-dialog" style="width:80%;">
					<div class="modal-content">
						<div class="modal-header">
							<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
							<h4 class="modal-title"><font color="red">用户权限分配</font>&nbsp;<font id="model_span_title_user_name" class="f14 text-info"></font></h4>
							<div class="lh25 pt5 f12 text-danger">
								<i class="fa fa-info-circle"></i> 关键提示：授权完成后，被授权用户退出系统进行重新登录后，即可生效！
							</div>
						</div>
						<div class="modal-body">
							<form class="form-horizontal" role="form" id="actForm">
								<input name="userId" id="act-userId" type="hidden">
								<!-- Custom Tabs -->
								<div class="nav-tabs-custom">
									<ul class="nav nav-tabs">
										<li class="active"><a href="#tab_3" data-toggle="tab" onclick="getActListData('0');">直接分配的操作权限</a></li>
									</ul>
									<div class="tab-content">
										<!-- /.tab-pane -->
										<div class="tab-pane active" id="tab_3">
											<table id="table3" class="table table-bordered table-hover" >
												<thead>
												<tr>
													<th>权限名称</th>
													<th>权限英文全称</th>
													<th>操作</th>
												</tr>
												</thead>
												<tbody id="userActList"></tbody>
											</table>
										</div>
										<!-- /.tab-pane -->
										<!-- /.tab-pane -->
									</div>
									<!-- /.tab-content -->
								</div>
								<!-- nav-tabs-custom -->
							</form>
						</div>
					</div>
				</div>
			</div>

			<!-- Part 二、以下是template模板定义的模块区域 -->
			<script type="text/template" id="dataList-template">
				<? for ( var i = 0; i < rows.length; i++) {?>
				<tr>
					<td><?=(pageObj.currentPage-1)*10+(i+1)?></td>
					<!-- temp="dataList_template_content" start -->
					<td style='display:none;'><input type="hidden" name="input_primaryKey" obj-name="uctUserSys" primary="infoId" value="<?=strUtil.doNull(rows[i].uctUser.userId,'')?>"/></td>
					<td><?=strUtil.doNull(rows[i].uctUserSys.userEname,'')?></td>
					<td><?=strUtil.doNull(rows[i].uctUser.userCname,'')?></td>
					<td>
						<?if(rows[i].uctUser.delStatus=='0'){?>机构用户<?}?>
						<?if(rows[i].uctUser.delStatus=='2'){?>机构管理员<?}?>
						<?if(rows[i].uctUser.delStatus=='3'){?>系统管理员<?}?>
					</td>
					<td><?=strUtil.doNull(rows[i].uctUser.mobile,'')?></td>
					<td><?=getFormatDateByLong(rows[i].uctUserSys.createTime,'yyyy-MM-dd hh:mm:ss')?></td>
					<!-- temp="dataList_template_content" end -->
				</tr>
				<?}?>
			</script>
			<script type="text/template" id="actListData">
				<? for ( var i = 0; i < rows.length; i++) {?>
				<tr>
					<td style="display:none;"><?=rows[i].actId?></td>
					<td><?=rows[i].actCname?></td>
					<td><?=rows[i].fullEname?></td>
					<td><?=rows[i].fullCname?></td>
				</tr>
				<?}?>
			</script>

			<script type="text/template" id="userActListData">
				<? for ( var i = 0; i < rows.length; i++) {?>
				<tr id="<?=rows[i].uctAct.actId?>"  fatherId="<?=rows[i].uctAct.fatherId?>">
					<?if(rows[i].uctAct.subCount>0||"0"==rows[i].uctAct.fatherId){?>
					<td class="textLeft" id="css_<?=rows[i].uctAct.actId?>" title="当展开子级后可同步批量设置" onclick="getChildActsData('<?=rows[i].uctAct.fatherId?>','<?=rows[i].uctAct.actId?>','<?=rows[i].uctAct.fullEname?>',this);">
						<i class="fa fa-plus" ></i>&nbsp;<?=rows[i].uctAct.actCname?>
					</td>
					<?} else{?>
					<td class="textLeft" id="css_<?=rows[i].uctAct.actId?>">
						&nbsp;<?=rows[i].uctAct.actCname?>
					</td>
					<?}?>
					<td class="textLeft">
						<?=rows[i].uctAct.fullEname?>
					</td>
					<td <?if(rows[i].uctAct.subCount>0||"0"==rows[i].uctAct.fatherId){?>title="当展开子级后可同步批量设置"<?}?>>
						<input type="checkbox" name="input_act_ename" onclick="clickGiveRole(this)" <?if(myActGiveData[rows[i].uctAct.actId]){?>checked <?}?>
						sub-count="<?=rows[i].uctAct.subCount?>"
						full-ename="<?=rows[i].uctAct.fullEname?>" full-cname="<?=rows[i].uctAct.fullCname?>" value="<?=rows[i].uctAct.actId?>"/>
					</td>
				</tr>
				<?}?>
			</script>
			<!-- Part 三、 以下是js模块区域 -->
			<script>
                var clickMenu = "user-act-give";
                var myPage,dataListId,searchFormId;
                myPage = 10;//定义列表数据
                dataListId = "dataList";//显示列表数据div的id
                searchFormId = "searchForm";//搜索表单Id
                var userId,userEname,userCname;
                var defSysEname = strUtil.doNull(strUtil.getLocalStorage("sysEname"), "");
                var myActGiveData = {};
                /**
                 * 初始化数据字典，id传入#id 返回值Map用法：dictListMap["userType"][rows[i].userType]
                 */
                var dictListMap = DictUtil.initDictAndDymic();

                $(function () {
                    $("#searchForm_hidden").find("input[name='uctUserSys.w_sysNo']").val(defSysEname);
                    //1、加载分页列表数据
                    getTableData();
                    //2、控制是否启用token
                    //setToken();

                });

                $(function () {
                    //设置数据行选中效果
                    $('#'+dataListId+' tbody').on('click','tr', function (e) {
                        if ( $(this).hasClass('selected') ) {
                        }
                        else {
                            $('tr.selected').removeClass('selected');
                            $(this).addClass('selected');
                        }
                        //var id = $('tr.selected th').eq(0).html();
                        userId = $('tr.selected td').eq(1).find("input[name='input_primaryKey']").val();
                        userEname = $('tr.selected td').eq(2).html();
                        userCname = $('tr.selected td').eq(3).html();
                    } );
                });

                //打开添加modal
                function toAddAct(){
                    if(strUtil.isNull(userId)){
                        layer.alert("请先选中一个用户数据！");
                        return;
                    }
                    $("#model_span_title_user_name").text(" [被授权用户："+userEname+"->"+userCname+"]");
                    getActListData("0");
                    $("#my_modal_act").modal("show");
                }
                function getTableData(){
                    $.ajax({
                        type:'get',
                        url:common_list_url,
                        data:$("#"+searchFormId).serialize()+getCurrentPage(common_list_url+"?"+$("#"+searchFormId).serialize(),myPage),
                        dataType:'json',
                        success: function(myData){
                            console.log(myData);
                            var data = baidu.template(dataListId+"-template",eval(myData));
                            $("#"+dataListId+"-body").html(data);
                            var option= {
                                ele:$("#"+dataListId+"-page")[0],
                                total:myData.total,
                                fn:getTableData,
                                url:common_list_url+"?"+$("#"+searchFormId).serialize()
                            }
                            generatePages(option);
                        }
                    });
                }

                //查询我选中的权限
                function getMyActGiveData(userId){
                    myActGiveData={};
                    var index_load = layer.load(1, {shade: false});
                    $.ajax({type:'get',
                        url:common_list_url,async: false,
                        data:{'pageName':'uct-act-give-list','formName':'searchForm','uctActGive.w_sysEname':defSysEname,'uctActGive.w_giveType':'user','uctActGive.w_roleId':userId},
                        dataType:'json',
                        success: function(myData){
                            console.log("myActGiveData",myData);
                            layer.close(index_load);
                            if(myData.flag=='T'&& myData.total>0){
                                for(var i=0;i<myData.rows.length;i++){
                                    var giveObj = myData.rows[i].uctActGive;
                                    var key = giveObj.actId;
                                    var val = giveObj.actFullEname;
                                    myActGiveData[key]=val;
                                }
                            }
                        }
                    });
                }

                //加载定义的该系统所有权限数据
                function getActListData(fatherId){
                    $("#userActList").html("");
                    var index_load = layer.load(1, {shade: false});
                    getMyActGiveData(userId);
                    console.log("myActGiveDataMap",myActGiveData);
                    $.ajax({type:'get',
                        url:common_list_url,
                        data:{'pageName':'uct-act-list','formName':'searchForm','uctAct.w_sysEname':defSysEname,'uctAct.w_fatherId':'0'},
                        dataType:'json',
                        success: function(myData){
                            console.log("uct-act-myData",myData);
                            layer.close(index_load);
                            if(myData.total>0){
//                                myData.myActGiveData=myActGiveData;
                                var data = baidu.template('userActListData',eval(myData));
//                                alert(data);
                                $("#userActList").html(data);
                            }
                        }
                    });
                }
                function getChildActsData(fatherId,actId,treeLevel,obj){
                    // alert(fatherId+"------"+actId+"------"+treeLevel+"------"+obj)
                    var count =0;
                    var ss = treeLevel.split("/");
                    count = ss.length-1;
                    $.ajax({ type:'get',url:common_list_url,
                        data:{'pageName':'uct-act-list','formName':'searchForm','uctAct.w_fatherId':actId,'uctAct.w_sysEname':defSysEname,'orderBy':'uctAct.order_num'},
                        dataType:'json',
                        success: function(myData){
                            console.log(myData);
                            var data = baidu.template('userActListData',myData);
                            if($(obj).find("i").hasClass("fa-minus")){
                                $(obj).find("i").attr("class","fa fa-plus");
                                delActsChiled(actId);
                            }else{
                                $(obj).find("i").attr("class","fa fa-minus");
                                $("#"+actId).after(data);
                                $("[fatherid='"+actId+"']").each(function(i){
                                    var thisObj = $(this);
                                    var pd = "10px 20px 10px ";
                                    var num = pd+(count*20)+"px";
                                    $(thisObj).find("td").eq(0).css("padding",num);
                                });
                            }
                        }
                    });
                }
                function delActsChiled(id){
                    $("[fatherid='"+id+"']").each(function(i){
                        var thisObj = $(this);
                        $(thisObj).remove();
                        var id = thisObj.attr("id");
                        delActsChiled(id);
                    });
                }
                //新增或者删除权限数据公用方法
                function addUpdateActGive(isAdd,actId,fullEname,userId,userEname) {
                    var result = false;
                    if(strUtil.isNull(actId) || strUtil.isNull(fullEname)){
                        return result;
                    }
                    var index_load = layer.load(1, {shade: false});
                    var flag = "add";
                    if(isAdd){
                        flag = "add";
                        console.log("+"+userEname,actId+"->"+fullEname);
					}else{
                        flag = "del";
                        console.log("-"+userEname,actId+"->"+fullEname);
                    }
                    $.ajax({type: "post",async: false,
                        url: ctx+"/res/uct/admin/authorizeAct?actGiveType=user&flag="+flag+"&id="+actId+"&objId="+userId,
                        success: function(resultData){
							var myData = JSON.parse(resultData);
                             layer.close(index_load);
                            if(myData.flag=="T"){
                                result = true;
                            }else{
                                console.log("uctActGive",myData);
                                layer.msg("授权操作操作失败，请重新尝试！");
                            }
                        }
                    });
                    return result;
                }
                //点击授权
                function clickGiveRole(ob) {
                    var result = false;
                    var obj = $(ob);
                    var userActListObjBody = $("#userActList");
                    var thisActId = obj.val();
                    var thisfullEname=obj.attr("full-ename");
                    var thisSubCount = obj.attr("sub-count");
                    var thisFatherId = obj.parent().parent().attr("fatherid");
                    var isAdd = false;
                    if(obj.is(":checked")){
                        isAdd = true;
                    }else{
                        isAdd = false;
                    }
                    //1、新增、删除当前对象
                    result = addUpdateActGive(isAdd,thisActId,thisfullEname,userId,userEname);

                    //2、表示有子级 && 是展开状态，则开始批量授权（或取权）子项
                    var iObj = obj.parent().parent().find("i");//处理子级
                    if(!strUtil.isNull(thisSubCount) && thisSubCount*1>0 && iObj && iObj.hasClass("fa-minus")){
                        userActListObjBody.find("tr[fatherid="+thisActId+"]").each(function () {
                            var inputActObj = $(this).find("input[type='checkbox'][name='input_act_ename']");
                            var childActId = inputActObj.val();
                            var childfullEname = inputActObj.attr("full-ename");
                            if(isAdd && !inputActObj.is(":checked")){
                                result = addUpdateActGive(isAdd,childActId,childfullEname,userId,userEname);
                                inputActObj.prop("checked",true);
                            }
                            if(!isAdd && inputActObj.is(":checked")){
                                result = addUpdateActGive(isAdd,childActId,childfullEname,userId,userEname);
                                inputActObj.prop("checked",false);
                            }
                        });
                    }

					//3、非顶级+子级勾选时 情况下 限。
                    if(thisFatherId!='0'){
                        var fatherCheckObx = userActListObjBody.find("tr[id="+thisFatherId+"]").find("input[type='checkbox'][name='input_act_ename']");
                        var fatherActId = fatherCheckObx.val();
                        var fatherfullEname = fatherCheckObx.attr("full-ename");
                        if(isAdd){
                            //当选中后发现父级未选中，则自动在此选中父级
                            if(!fatherCheckObx.is(":checked")){
                                console.log("同步选中父级勾选状态：",thisFatherId+"->"+fatherfullEname);
                                result = addUpdateActGive(isAdd,fatherActId,fatherfullEname,userId,userEname);
                                fatherCheckObx.prop("checked",true);
							}
						}else{
						    //当全部取消所有兄弟权限后，自动也同步取消父级选中的权
                            var borderCheckedCount = userActListObjBody.find("tr[fatherid="+thisFatherId+"]").find("input[type='checkbox']:checked").length;
//                            console.log("同级剩余已勾选个数：",borderCheckedCount);
                            if(borderCheckedCount==0){
                                isAdd = false;
                                console.log("同步取消父级勾选状态：",thisFatherId+"->"+fatherfullEname);
                                result = addUpdateActGive(isAdd,fatherActId,fatherfullEname,userId,userEname);
                                fatherCheckObx.prop("checked",false);
                            }
						}
                    }

                }

                //刷新
                function refresh(){
                    userId="",userCname="";
                    getTableData();
                }
                //设置token
                function setToken(){
                    $.ajax({
                        type:'get',
                        url:'${ctx}/sendPage/token?token=true',
                        dataType:'text',
                        success: function(myData){
                            console.log(myData);
                            $('.formToken').val(myData);
                        }
                    });
                }

			</script>
		</section>
		<!-- Main end -->
	</div>
</div>

<!-- /.content-wrapper -->
<!-- foot start -->
<%@include file="/common/plateform/foot.jsp" %>
<!-- foot start -->
</body>
</html>

